import sys
from PyQt4 import QtGui, QtCore


class MainGUI(QtGui.QWidget):
    
    def __init__(self):
        super(MainGUI, self).__init__()
        self.initUI()
        
    def initUI(self):
        
        layout = QtGui.QGridLayout()

        self.input_file_label = QtGui.QLabel('Select an XML file:')
        layout.addWidget(self.input_file_label, 0, 0, 1, 1)

        self.input_file_path = QtGui.QLineEdit()
        layout.addWidget(self.input_file_path, 1, 0, 1 , 9)

        self.input_file_browse = QtGui.QPushButton('Browse')
        layout.addWidget(self.input_file_browse, 1, 9, 1 , 1)
        self.input_file_browse.released.connect(self.open_file)

        self.xml_input_label = QtGui.QLabel('XML input:')
        layout.addWidget(self.xml_input_label, 2, 0, 1 , 5)

        self.xml_input = QtGui.QTextEdit()
        layout.addWidget(self.xml_input, 3, 0, 5 , 5)

        self.csv_output_label = QtGui.QLabel('CSV output:')
        layout.addWidget(self.csv_output_label, 2, 5, 1 , 5)

        self.csv_output = QtGui.QTextEdit()
        layout.addWidget(self.csv_output, 3, 5, 5 , 5)

        self.output_file_label = QtGui.QLabel('Output filename:')
        layout.addWidget(self.output_file_label, 8, 0, 1, 1)

        self.output_file_path = QtGui.QLineEdit()
        layout.addWidget(self.output_file_path, 9, 0, 1 , 9)

        self.output_file_browse = QtGui.QPushButton('Browse')
        layout.addWidget(self.output_file_browse, 9, 9, 1 , 1)
        self.output_file_browse.released.connect(self.save_file)

        self.convert_button = QtGui.QPushButton('Convert')
        layout.addWidget(self.convert_button, 10, 5, 1 , 1)

        self.setLayout(layout)   
        self.resize(720, 650)
        self.setWindowTitle('XML to CSV Converter')    
        self.show()

    def open_file(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Select XML file', '.', 'XML files (*.xml);;All files (*.*)')
        openedFile = open(filename)
        content = openedFile.read()
        self.input_file_path.setText(filename)
        self.xml_input.setText(content)
        openedFile.close()

    def save_file(self):
        filename = QtGui.QFileDialog.getSaveFileName(self, 'Save As', '.')
        openedFile = open(filename, 'w')
        openedFile.write(self.csv_output.toPlainText())
        self.output_file_path.setText(filename)
        openedFile.close() 

        
def main():
    
    app = QtGui.QApplication(sys.argv)
    mainGUI = MainGUI()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
